﻿using System.Linq;
using Application.BusinessTypeService;
using Application.CodeRuleService;
using Application.ProductService;
using Application.ProductTypeService;
using Application.SupplierService;
using Application.WarehouseService;
using Domain.Entity;
using Domain.Entity.bs;
using Domain.Entity.sys;
using Domain.Entity.zct;
using EFCore.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;

namespace WMSManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]//需要鉴权
    public class WarehouseController : ControllerBase
    {
        private readonly IWarehouseService warehouseService;

        public WarehouseController(IWarehouseService warehouseService)
        {
            this.warehouseService = warehouseService;
        }


        /// <summary>
        /// 分页查询仓库表信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Warehouse>> GetWarehouse(int? status, string? whname, string? whdepname, string? whusername, int CurrentPage)
        {
            FenYe<Warehouse> fenYe = new FenYe<Warehouse>()
            {
                CurrentPage = CurrentPage,
            };
            return await warehouseService.GetWarehouse(fenYe, status, whname, whdepname, whusername);
        }

        /// <summary>
        /// 添加仓库表信息
        /// </summary>
        /// <param name="addWarehouseDto">仓库DTO对象</param>
        /// <returns>新创建的仓库ID</returns>
        [HttpPost]
        public async Task<IActionResult> AddWarehouse([FromBody] AddWarehouseDto addWarehouseDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                int newWarehouseId = await warehouseService.AddWarehouse(addWarehouseDto);
                return Ok(newWarehouseId); // 确保返回纯ID，不是复杂对象
            }
            catch (Exception ex)
            {
                // 记录详细日志
                Console.WriteLine($"添加仓库失败: {ex.Message}\n{ex.StackTrace}");
                return StatusCode(500, "服务器内部错误，请联系管理员");
            }
        }


        /// <summary>
        /// 根据用户姓名获取联系电话
        /// </summary>
        /// <param name="userName">用户姓名</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetPhoneByUserName(string userName)
        {
            try
            {
                var phone = await warehouseService.GetPhoneByUserName(userName);
                return Ok(new { code = 200, data = phone });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = ex.Message });
            }
        }



        /// <summary>
        /// 修改仓库表信息
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateWarehouse([FromBody] UpdateWarehouseDto updateWarehouse)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new
                {
                    code = 400,
                    message = "数据验证失败",
                    errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                });
            }

            if (updateWarehouse == null)
            {
                return BadRequest(new { code = 400, message = "请求体不能为空" });
            }

            if (updateWarehouse.wh_id <= 0)
            {
                return BadRequest(new { code = 400, message = "无效的仓库ID" });
            }

            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(updateWarehouse.wh_name))
                {
                    return BadRequest(new { code = 400, message = "仓库名称不能为空" });
                }

                var result = await warehouseService.UpdateWarehouse(updateWarehouse);
                if (result > 0)
                {
                    return Ok(new { code = 200, message = "修改成功", data = result });
                }
                return NotFound(new { code = 404, message = "未找到该仓库或未修改任何数据" });
            }
            catch (KeyNotFoundException ex)
            {
                return NotFound(new { code = 404, message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, message = $"服务器错误: {ex.Message}" });
            }
        }

        /// <summary>
        /// 查询仓库主管信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<User>> GetAllUsers()
        {
            return await warehouseService.GetAllUsers();
        }

        /// <summary>
        /// 查询仓库名
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Warehouse>> GetWarehouses()
        {
            return await warehouseService.GetWarehouses();
        }




        /// <summary>
        /// 删除仓库信息
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> DeleteWarehouse(int id)
        {
            return await warehouseService.DeleteWarehouse(id);
        }

        /// <summary>
        /// 根据id查询仓库信息
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetIdWarehouse(int id)
        {
            try
            {
                var result = await warehouseService.GetIdWarehouse(id);

                if (result == null)
                {
                    return NotFound(); // 返回 404 如果未找到
                }

                return Ok(result); // 确保返回 200 和数据
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        /// <summary>
        /// 导入仓库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [DisableRequestSizeLimit]
        public async Task<IActionResult> ImportWarehouses()
        {
            // 1. 验证请求
            if (!Request.HasFormContentType)
                return BadRequest(new { success = false, message = "请求必须包含表单数据" });

            var form = await Request.ReadFormAsync();
            var file = form.Files["file"];

            if (file == null || file.Length == 0)
                return BadRequest(new { success = false, message = "请上传有效的Excel文件" });

            // 2. 验证文件类型
            var allowedTypes = new[] {
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.ms-excel"
    };
            if (!allowedTypes.Contains(file.ContentType))
                return BadRequest(new { success = false, message = "只支持.xlsx或.xls格式的Excel文件" });

            // 3. 处理文件
            try
            {
                using var stream = new MemoryStream();
                await file.CopyToAsync(stream);
                stream.Position = 0;

                using var package = new ExcelPackage(stream);
                var worksheet = package.Workbook.Worksheets[0];

                if (worksheet.Dimension == null)
                    return BadRequest(new { success = false, message = "Excel文件中没有数据" });

                // 4. 读取表头验证
                var headers = Enumerable.Range(1, worksheet.Dimension.Columns)
                    .Select(col => worksheet.Cells[1, col].Value?.ToString()?.Trim())
                    .ToList();

                var requiredColumns = new[] { "序号","仓库编号", "仓库名称", "仓库容量/m3", "仓库地址", "库管部门", "仓库主管","库位数量","仓库状态","操作人","操作时间" };
                foreach (var column in requiredColumns)
                {
                    if (!headers.Contains(column))
                        return BadRequest(new
                        {
                            success = false,
                            message = $"Excel文件中缺少必要的列: '{column}'"
                        });
                }

                // 5. 获取现有数据用于重复检查
                var existingWarehouses = await warehouseService.GetWarehouses();
                var existingCodes = new HashSet<string>(existingWarehouses.Select(x => x.wh_code));
                var existingNames = new HashSet<string>(existingWarehouses.Select(x => x.wh_name));

                // 6. 处理数据行
                var result = new ImportResult
                {
                    SuccessCount = 0,
                    DuplicateCount = 0,
                    Errors = new List<string>()
                };

                for (int row = 2; row <= worksheet.Dimension.Rows; row++)
                {
                    try
                    {
                        var warehouse = new Warehouse();
                        bool isValid = true;

                        // 读取各列数据
                        for (int col = 1; col <= worksheet.Dimension.Columns; col++)
                        {
                            var header = headers[col - 1];
                            var value = worksheet.Cells[row, col].Value?.ToString()?.Trim();

                            try
                            {
                                switch (header)
                                {
                                    case "仓库编号":
                                        if (string.IsNullOrEmpty(value))
                                        {
                                            result.Errors.Add($"第{row}行: 仓库编号不能为空");
                                            isValid = false;
                                        }
                                        warehouse.wh_code = value;
                                        break;
                                    case "仓库名称":
                                        if (string.IsNullOrEmpty(value))
                                        {
                                            result.Errors.Add($"第{row}行: 仓库名称不能为空");
                                            isValid = false;
                                        }
                                        warehouse.wh_name = value;
                                        break;
                                    case "仓库容量/m3":
                                        if (string.IsNullOrEmpty(value))
                                        {
                                            result.Errors.Add($"第{row}行: 仓库容量不能为空");
                                            isValid = false;
                                        }
                                        else if (!int.TryParse(value, out int capacity) || capacity <= 0)
                                        {
                                            result.Errors.Add($"第{row}行: 仓库容量必须是大于0的整数");
                                            isValid = false;
                                        }
                                        else
                                        {
                                            warehouse.wh_capacity = capacity;
                                        }
                                        break;

                                    case "库位数量":
                                        if (string.IsNullOrEmpty(value))
                                        {
                                            result.Errors.Add($"第{row}行: 库位数量不能为空");
                                            isValid = false;
                                        }
                                        else if (!int.TryParse(value, out int slotNum) || slotNum < 0)
                                        {
                                            result.Errors.Add($"第{row}行: 库位数量必须是大于等于0的整数");
                                            isValid = false;
                                        }
                                        else
                                        {
                                            warehouse.wh_slot_num = slotNum;
                                        }
                                        break;

                                    case "仓库状态":
                                        if (string.IsNullOrEmpty(value))
                                        {
                                            result.Errors.Add($"第{row}行: 仓库状态不能为空");
                                            isValid = false;
                                        }
                                        else
                                        {
                                            switch (value.ToLower())
                                            {
                                                case "正常":
                                                case "启用":
                                                    warehouse.wh_status = 0;
                                                    break;
                                                case "停用":
                                                    warehouse.wh_status = 1;
                                                    break;
                                                default:
                                                    result.Errors.Add($"第{row}行: 仓库状态值无效，必须是 '正常' 或 '停用'");
                                                    isValid = false;
                                                    break;
                                            }
                                        }
                                        break;
                                    case "仓库地址":
                                            warehouse.wh_address = value;
                                        break;
                                    case "库管部门":
                                        warehouse.wh_depName = value;
                                        break;
                                    case "仓库主管":
                                        warehouse.wh_userName = value;
                                        break;
                                    case "操作人":
                                        warehouse.create_name = value;
                                        break;
                                    case "操作时间":
                                        warehouse.wh_address = value?.ToString() ?? string.Empty;
                                        break;
                                       
                                }
                            }
                            catch (Exception ex)
                            {
                                result.Errors.Add($"第{row}行 '{header}' 格式错误: {ex.Message}");
                                isValid = false;
                            }

                        
                        }


                        if (!isValid) continue;

                        // 检查重复
                        if (existingCodes.Contains(warehouse.wh_code))
                        {
                            result.Errors.Add($"第{row}行: 仓库编号 {warehouse.wh_code} 已存在");
                            result.DuplicateCount++;
                            continue;
                        }

                        // 添加新仓库
                        var dto = new AddWarehouseDto
                        {
                            wh_code = warehouse.wh_code,
                            wh_name = warehouse.wh_name,
                            wh_capacity = warehouse.wh_capacity,
                            wh_depName = warehouse.wh_depName,
                            wh_userName = warehouse.wh_userName,
                            wh_address = warehouse.wh_address,
                            wh_slot_num = (int)warehouse.wh_slot_num,
                            wh_status = warehouse.wh_status,
                            create_name = warehouse.create_name,
                            create_time = (warehouse.create_time ?? DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss"),
                            is_default = 0,
                            wh_depId = 0,
                            wh_userId = 0,
                            wh_sort = 0,
                            is_lock = 0,
                        };
                        // 插入数据库
                        try
                        {
                            var addResult = await warehouseService.AddWarehouse(dto);
                            if (addResult > 0)
                            {
                                result.SuccessCount++;
                            }
                            else
                            {
                                result.Errors.Add($"第{row}行: 数据库插入失败");
                            }
                        }
                        catch (Exception ex)
                        {
                            result.Errors.Add($"第{row}行: 数据库异常 - {ex.Message}");
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Errors.Add($"第{row}行处理失败: {ex.Message}");
                    }
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = "服务器处理文件时出错",
                    error = ex.Message
                });
            }
        }



        /// <summary>
        /// 分页高级查询
        /// </summary>
        /// <param name="code"></param>
        /// <param name="userName"></param>
        /// <param name="name"></param>
        /// <param name="minCapacity"></param>
        /// <param name="maxCapacity"></param>
        /// <param name="status"></param>
        /// <param name="minNum"></param>
        /// <param name="maxNum"></param>
        /// <param name="depName"></param>
        /// <param name="time"></param>
        /// <param name="status"></param>
        /// <param name="CurrentPage"></param>
        /// <returns></returns>
        [HttpGet]
        //分页高级查询
        public async Task<FenYe<Warehouse>> GetvancedWarehouse(string? code, string? userName, string? name, string? minCapacity, string? maxCapacity, int? status, string? minNum, string? maxNum, string? depName, string? time ,int CurrentPage)
        {
            FenYe<Warehouse> fenYe = new FenYe<Warehouse>()
            {
                CurrentPage = CurrentPage,
            };
            return await warehouseService.GetvancedWarehouse(fenYe, code, userName, name, minCapacity, maxCapacity, status, minNum, maxNum, depName, time);
        }

        /// <summary>
        /// 修改仓库状态
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdateStatus(int wh_id,int wh_status)
        {
            return await warehouseService.UpdateStatus(wh_id, wh_status);
        }

        // 导入结果模型
        public class ImportResult
        {
            public int SuccessCount { get; set; }
            public int DuplicateCount { get; set; }
            public List<string> Errors { get; set; }
        }



        /// <summary>
        /// 锁定/解锁仓库
        /// </summary>
        /// <param name="whid"></param>
        /// <param name="islock"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> LockWarehouse(int whid, int islock)
        {
            return await warehouseService.LockWarehouse(whid, islock);
        }

    }
}